package cn.miao.photoprinter.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import cn.miao.photoprinter.R;
import cn.miao.photoprinter.entity.PhotoCheckItem;

import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

public class Util {

	public static void initImageLoader(Context context) {
		DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.empty_photo)
				.showImageForEmptyUri(R.drawable.empty_photo)
				.showImageOnFail(R.drawable.empty_photo).cacheInMemory(true)
				.considerExifParams(true)
				.displayer(new FadeInBitmapDisplayer(300, true, true, true))
				.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
		ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
				context).defaultDisplayImageOptions(defaultOptions)
				.memoryCache(new WeakMemoryCache());
		ImageLoaderConfiguration config = builder.build();
		ImageLoader.getInstance().init(config);
	}

	public static void deleteAlbumFile(Context context) {
		try {
			final String[] columns = { MediaStore.Images.Media.DATA,
					MediaStore.Images.Media._ID,
					MediaStore.Images.Media.DATE_TAKEN };
			final String orderBy = MediaStore.Images.Media.DATE_TAKEN + " DESC";
			Cursor imagecursor = context.getContentResolver().query(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
					null, null, orderBy);
			if (null != imagecursor && imagecursor.getCount() > 0) {
				imagecursor.moveToFirst();
				imagecursor.moveToNext();
				String imageUri = imagecursor.getString(imagecursor
						.getColumnIndex(MediaStore.Images.Media.DATA));
				String id = imagecursor.getString(imagecursor
						.getColumnIndex(MediaStore.Images.Media._ID));
				int rows = context.getContentResolver().delete(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
						MediaStore.Images.Media._ID + "=" + id, null);

				// Remove file from card
				if (rows != 0) {
					try {
						File f = new File(imageUri);
						System.out.println("remove " + imageUri);
						f.delete();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static int getGalleryCount(Context context) {
		try {
			final String[] columns = { MediaStore.Images.Media.DATA,
					MediaStore.Images.Media._ID,
					MediaStore.Images.Media.DATE_TAKEN };
			final String orderBy = MediaStore.Images.Media.DATE_TAKEN + " DESC";
			Cursor imagecursor = context.getContentResolver().query(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
					null, null, orderBy);
			if (null != imagecursor && imagecursor.getCount() > 0) {
				return imagecursor.getCount();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	public static Map<String, Object> getGalleryPhotos(Context context) {
		Map<String, Object> rtMap = new HashMap<String, Object>();
		ArrayList<PhotoCheckItem> galleryList = new ArrayList<PhotoCheckItem>();
		Map<String, Integer> sectionInfo = new LinkedHashMap<String, Integer>();
		try {
			final String[] columns = { MediaStore.Images.Media.DATA,
					MediaStore.Images.Media._ID,
					MediaStore.Images.Media.DATE_TAKEN };
			final String orderBy = MediaStore.Images.Media.DATE_TAKEN + " DESC";
			Cursor imagecursor = context.getContentResolver().query(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
					null, null, orderBy);
			PhotoCheckItem photoCheckItem = null;
			if (imagecursor != null && imagecursor.getCount() > 0) {
				while (imagecursor.moveToNext()) {
					String item = new String();
					photoCheckItem = new PhotoCheckItem();
					int dataColumnIndex = imagecursor
							.getColumnIndex(MediaStore.Images.Media.DATA);
					item = imagecursor.getString(dataColumnIndex);
					int dateColumnIndex = imagecursor
							.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN);
					DateFormat format = new SimpleDateFormat("yyyy年MM月dd日",
							Locale.CHINA);
					Date createDate = new Date(
							imagecursor.getLong(dateColumnIndex));
					String createDateStr = format.format(createDate);
					if (null == sectionInfo.get(createDateStr)) {
						sectionInfo.put(createDateStr, 1);
					} else {
						int tmp = sectionInfo.get(createDateStr) + 1;
						sectionInfo.put(createDateStr, tmp);
					}
					photoCheckItem.setPath(item);
					galleryList.add(photoCheckItem);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// Collections.reverse(galleryList);
		rtMap.put("photos", galleryList);
		rtMap.put("sections", sectionInfo);
		return rtMap;
	}

	public static Bitmap convertViewToBitmap(View view) {
		Bitmap bitmap = null;
		try {
			int width = view.getWidth();
			int height = view.getHeight();
			if (width != 0 && height != 0) {
				bitmap = Bitmap.createBitmap(width, height,
						Bitmap.Config.ARGB_8888);
				Canvas canvas = new Canvas(bitmap);
				view.layout(0, 0, width, height);
				view.setBackgroundColor(Color.WHITE);
				view.draw(canvas);
			}
		} catch (Exception e) {
			bitmap = null;
			e.getStackTrace();
		}
		return bitmap;

	}

	public static boolean saveImageToGallery(Context context, Bitmap bmp,
			boolean isPng) {
		File appDir = new File(Environment.getExternalStorageDirectory(),
				context.getString(R.string.app_name));
		if (!appDir.exists()) {
			if (!appDir.mkdir()) {
				return false;
			}
		}
		String fileName;
		if (isPng) {
			fileName = System.currentTimeMillis() + ".png";
		} else {
			fileName = System.currentTimeMillis() + ".jpg";
		}
		File file = new File(appDir, fileName);
		try {
			FileOutputStream fos = new FileOutputStream(file);
			if (isPng) {
				bmp.compress(CompressFormat.PNG, 100, fos);
			} else {
				bmp.compress(CompressFormat.JPEG, 100, fos);
			}
			bmp.recycle();
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		try {
			MediaStore.Images.Media.insertImage(context.getContentResolver(),
					file.getAbsolutePath(), fileName, null);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		}
		context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
				Uri.fromFile(appDir)));
		return true;
	}

	public static Object evaluate(float fraction, Object startValue,
			Object endValue) {
		int startInt = (Integer) startValue;
		int startA = (startInt >> 24) & 0xff;
		int startR = (startInt >> 16) & 0xff;
		int startG = (startInt >> 8) & 0xff;
		int startB = startInt & 0xff;
		int endInt = (Integer) endValue;
		int endA = (endInt >> 24) & 0xff;
		int endR = (endInt >> 16) & 0xff;
		int endG = (endInt >> 8) & 0xff;
		int endB = endInt & 0xff;
		return (int) ((startA + (int) (fraction * (endA - startA))) << 24)
				| (int) ((startR + (int) (fraction * (endR - startR))) << 16)
				| (int) ((startG + (int) (fraction * (endG - startG))) << 8)
				| (int) ((startB + (int) (fraction * (endB - startB))));
	}

	public static String listToString(List<String> paramList, String paramString) {
		if (paramList == null)
			return "";
		StringBuilder localStringBuilder = new StringBuilder("");
		for (int i = 0; i < paramList.size(); i++)
			if (i == paramList.size() - 1)
				localStringBuilder.append(((String) paramList.get(i)).trim());
			else
				localStringBuilder.append(((String) paramList.get(i)).trim()
						+ paramString);
		return localStringBuilder.toString();
	}

	public static List<String> stringsToList(String[] paramArrayOfString) {
		if ((paramArrayOfString == null) || (paramArrayOfString.length == 0))
			return null;
		ArrayList<String> localArrayList = new ArrayList<String>();
		for (int i = 0; i < paramArrayOfString.length; i++)
			localArrayList.add(paramArrayOfString[i]);
		return localArrayList;
	}

}
